<template>
  <div class="shopcart-container">
    <template v-if="cartList.length==0">
      <van-image :src="require('@/assets/images/shopcart_empty.png')" width="100%"></van-image>
    </template>
    <template v-else>
      <!-- 全选 清空  -->
      <div class="cart_header">
        <div>
          <!-- 全选 -->
          <van-checkbox checked-color="#000000" icon-size="18" v-model="isCheckedAll" @click="handleSelectAll">全选
          </van-checkbox>
        </div>
        <div class="button-delete-all" @click="handleDeleteAll">
          <van-icon name="delete" :size="18"/>
          <span>清空</span>
        </div>

      </div>
      <!-- 商品列表区域 -->
      <div class="cart-list">
        <van-row v-for="(item, i) in cartList" :key="i" type="flex" align="center">
          <van-col span="3">
            <!-- 复选框 -->
            <van-checkbox v-model="item.isChecked" @change="handleCheckedChange(item)"/>
          </van-col>

          <van-col span="5">
            <!-- 中间商品图片 -->
            <van-icon size="80" :name="$fullUrl(item.goodsImg)"></van-icon>
          </van-col>

          <van-col span="16">
            <van-row class="van-multi-ellipsis--l2 goods-name">{{ item.goodsName }}</van-row>
            <van-row type="flex" align="center">
              <van-col span="8" class="price">¥{{ item.goodsPrice }}</van-col>
              <van-col span="16" class="operation">
                <van-stepper v-model="item.count" @change="handleCountChanged(item)" integer/>
                <van-button text="删除" size="small" type="danger" @click.prevent="handleDeleteCartItem(item.id)"/>
              </van-col>
            </van-row>
          </van-col>
        </van-row>
      </div>

      <!-- 商品结算区域 -->
      <van-cell title="已选商品总金额" class="totalAmount">
        <template #default>
          <span class="red">¥{{ getCheckedAmount }}</span>
        </template>
      </van-cell>

      <!-- 结算按钮 -->
      <van-button type="primary" size="large" @click="handleCreateOrder">去结算</van-button>
    </template>

  </div>

</template>

<script>
//导入接口
import * as CartAPI from "@/api/cart.js";

export default {
  name: "Cart",
  data() {
    return {
      cartList: [], //购物车列表
      isCheckedAll: false, //是否全选
    };
  },

  //实例的生命周期函数，实例创建后被调用
  created() {
    this.getCartList(); //初始化购物车数据
  },

  computed: {
    getCheckedCount() { //计算勾选记录总数
      let sum = 0;
      this.cartList.forEach((item) => {
        if (item.isChecked) sum += 1;
      });
      return sum;
    },

    //计算是否全部勾选
    getCheckedAll() {
      return this.cartList.length == this.getCheckedCount ? true : false;
    },

    //统计购物车金额
    getCheckedAmount() {
      let amount = 0;
      this.cartList.forEach((item) => {
        if (item.isChecked) amount += item.goodsPrice * item.count;
      });
      return amount;
    },

  },

  methods: {
    //获取用户购物车数据
    getCartList() {
      this.cartList = []; //清空
      CartAPI.getMyList().then(result => {
        this.cartList = result.data;
        this.isCheckedAll = this.getCheckedAll; //同步是否全选
      }).catch(() => {
      });
    },

    //触发更改购物商品选中状态
    handleCheckedChange(item) {
      let id = item.id;
      let isChecked = item.isChecked;
      let params = {
        id,
        isChecked
      };
      CartAPI.update(params).then(() => {
        this.isCheckedAll = this.getCheckedAll; //同步是否全选
      }).catch(() => {
      });
    },

    //触发更改购物商品数量
    handleCountChanged(item) {
      let params = {
        id: item.id,
        count: item.count
      };
      CartAPI.update(params).then(() => {
      });
    },

    //触发删除购物商品
    handleDeleteCartItem(id) {
      let ids = [];
      ids.push(id);
      CartAPI.deleteByIds(ids).then(() => {
        this.getCartList(); //刷新列表数据
      });
    },

    //触发全选/全不选
    handleSelectAll() {
      //准备参数
      let isChecked = this.isCheckedAll;
      //调用接口
      CartAPI.updateIsCheckedAllByMy(isChecked).then(() => {
        this.getCartList(); //刷新列表数据
      });
    },

    //触发清空
    handleDeleteAll() {
      this.$dialog.confirm({
        message: '客官，您确定清空购物车吗?'
      }).then(() => {
        CartAPI.deleteAllByMy().then(() => {
          this.getCartList(); //刷新列表数据
        });
      })
    },

    //触发创建订单
    handleCreateOrder() {
      if (this.cartList.length === 0) {
        this.$toast("您的购物车为空");
        return;
      }

      //this.$toast("这个路由功能还没实现...");
      this.$router.push({
        name: "orderCreate"
      });
    },
  }
}
</script>

<style lang="less" scoped="scoped">
.shopcart-container {
  background-color: white;

  .cart_header {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid lightgrey;
    font-size: 14px;
    line-height: 30px;
  }
}

.button-delete-all {
  display: flex;
  align-items: center;
}

.van-row {
  padding: 5px 0;
}

.van-col .van-checkbox {
  justify-content: center;
}

.goods-name {
  padding: 5px 10px;
  font-size: 12px;
}

.price {
  padding-left: 10px;
  text-align: left;
  font-size: 14px;
  font-weight: bold;
  color: red;
  display: flex;
  align-items: center;
}

.operation {
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.red {
  color: red;
  font-weight: bold;
  font-size: 14px;
}
</style>
